<template>
  <div class="background">
    <div style="padding: 0 0 15px 15px;">
      <a-row>
        <a-col :span="10">
          <a-space>
            <a-button icon="left" @click.stop="goPrev"/>
            <a-date-picker v-model:value="currentMonth" placeholder="选择日期" :allowClear="false" @change="onChangeDate"/>
            <a-button icon="right" @click.stop="goNext"/>
          </a-space>
        </a-col>
        <a-col :span="5">
          <h3 style="margin:0;font-size:18px;font-weight: bold;">梳棉计划产量</h3>
        </a-col>
        <a-col :span="8">
          <a-space style="float: right;">
            <a-button type="primary" icon="plus-circle" @click="handleAdd">新增计划</a-button>
            <a-button icon="plus-circle">复制昨日日计划</a-button>
            <a-button icon="plus-circle">导出日计划</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
    <div class="XiSha" style="margin-top: 10px;padding:15px;">
      <a-table ref="table"
               rowKey="id"
               :columns="columns"
               :dataSource="dataSource"
               :pagination="ipagination"
               :loading="loading"
               @change="handleTableChange"
               :scroll="{ x: 3500}">
        <div slot="车间" slot-scope="text,record">
          <j-dict-select-tag v-model="text" dictCode="workshop" style="width: 80px;"
                             @change="selectChange(text,'workshop',record)"/>
        </div>
        <div slot="工序" slot-scope="text,record">
          <span>梳棉</span>
        </div>
        <div slot="前纺品种" slot-scope="text,record">
          <j-dict-select-tag v-model="text" dictCode="crm_product_type_cotton,product_type,id" style="width: 150px;"
                             @change="selectChange(text,'cproductType',record)"/>
        </div>
        <div slot="机号" slot-scope="text,record">
          <a-space>
            <div v-html="getSeiresDevsnCs(record['preSpinDevices'])"></div>
            <a-button type="primary" ghost size="small" icon="plus" @click="showModal(record,'preSpinDevices')"></a-button>
          </a-space>
        </div>
        <div slot="甲A开台" slot-scope="text,record" style="display: flex;justify-content: center;">
          <a-space>
            <div v-html="getSeiresDevsnCs(record['adevices'])"></div>
            <a-button type="primary" ghost size="small" icon="plus"
                      @click="showModal(record,'adevices')"></a-button>
          </a-space>
        </div>
        <div slot="乙B开台" slot-scope="text,record" style="display: flex;justify-content: center;">
          <a-space>
            <div v-html="getSeiresDevsnCs(record['bdevices'])"></div>
            <a-button type="primary" ghost size="small" icon="plus"
                      @click="showModal(record,'bdevices')"></a-button>
          </a-space>
        </div>
        <div slot="丙C开台" slot-scope="text,record" style="display: flex;justify-content: center;">
          <a-space>
            <div v-html="getSeiresDevsnCs(record['cdevices'])"></div>
            <a-button type="primary" ghost size="small" icon="plus"
                      @click="showModal(record,'cdevices')"></a-button>
          </a-space>
        </div>
        <div slot="锭数" slot-scope="text,record">
          <div v-if="record.bcProductType == record.acProductType">
            <span>{{ record.acProductTypeInfo.ingots }}</span>
          </div>
          <div v-else>
            <span>{{ record.acProductTypeInfo.ingots + '/' + record.bcProductTypeInfo.ingots }}</span>
          </div>
        </div>
        <div slot="定量" slot-scope="text,record">
          <div v-if="record.bcProductType == record.acProductType">
            <span>{{ record.acProductTypeInfo.ration }}</span>
          </div>
          <div v-else>
            <span>{{ record.acProductTypeInfo.ration + '/' + record.bcProductTypeInfo.ration }}</span>
          </div>
        </div>
        <div slot="车速" slot-scope="text,record">
          <div v-if="record.bcProductType == record.acProductType">
            <span>{{ record.acProductTypeInfo.speed }}</span>
          </div>
          <div v-else>
            <span>{{ record.acProductTypeInfo.speed + '/' + record.bcProductTypeInfo.speed }}</span>
          </div>
        </div>
        <div slot="效率" slot-scope="text,record">
          <div v-if="record.bcProductType == record.acProductType">
            <span>{{ record.acProductTypeInfo.efficiency }}</span>
          </div>
          <div v-else>
            <span>{{ record.acProductTypeInfo.efficiency + '/' + record.bcProductTypeInfo.efficiency }}</span>
          </div>
        </div>
        <!--        <div slot="定额" slot-scope="text,record">-->
        <!--          <div v-if="record.bbProductType == record.abProductType">-->
        <!--            <span>{{ record.arProductTypeInfo.weight }}</span>-->
        <!--          </div>-->
        <!--          <div v-else>-->
        <!--            <span>{{ record.arProductTypeInfo.weight + '/' + record.brProductTypeInfo.weight }}</span>-->
        <!--          </div>-->
        <!--        </div>-->
        <div slot="action" slot-scope="text,record">
          <a-popconfirm
            title="确认要移除吗?"
            ok-text="是"
            cancel-text="否"
            @confirm="handleDelete(record.id)"
          >
            <a href="#">移出</a>
          </a-popconfirm>
        </div>
      </a-table>
    </div>
    <shumian-modal ref="modalForm" @ok="modalFormOk"></shumian-modal>
    <shu-mian-ji-tai-modal ref="jitaiModal"></shu-mian-ji-tai-modal>
  </div>
</template>

<script>
import moment from 'moment'
import ShumianModal from './modules/ShumianModal'
import ShuMianJiTaiModal from './modules/ShuMianJiTaiModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { editDailyPlanPreSpin } from '../../../api/customApi'

const path = '/crm_daily_plan_pre_spin/crmDailyPlanPreSpin'

const columns = [
  {
    title: '车间',
    dataIndex: 'workshop',
    align: 'center',
    key: 'workshop',
    scopedSlots: { customRender: '车间' },
  },
  {
    title: '工序',
    dataIndex: 'process',
    align: 'center',
    key: 'process',
    scopedSlots: { customRender: '工序' },
  },
  {
    title: '前纺品种',
    dataIndex: 'cproductType',
    width: 150,
    align: 'center',
    key: 'cproductType',
    scopedSlots: { customRender: '前纺品种' },
  },
  {
    title: '机号',
    width: 200,
    align: 'center',
    dataIndex: 'preSpinDevices',
    key: 'preSpinDevices',
    scopedSlots: { customRender: '机号' },
  },
  {
    title: '计划台数24h',
    align: 'center',
    width: 150,
    dataIndex: 'planOpen',
    key: 'planOpen',
  },
  {
    title: '甲A开台8h',
    dataIndex: 'adeviceIds',
    align: 'center',
    key: 'adeviceIds',
    width: 200,
    scopedSlots: { customRender: '甲A开台' },
  },
  {
    title: '乙B开台8h',
    dataIndex: 'bdeviceIds',
    align: 'center',
    key: 'bdeviceIds',
    width: 200,
    scopedSlots: { customRender: '乙B开台' },
  },
  {
    title: '丙C开台8h',
    align: 'center',
    width: 220,
    dataIndex: 'cdeviceIds',
    key: 'cdeviceIds',
    scopedSlots: { customRender: '丙C开台' },
  },
  {
    title: '锭数',
    width: 100,
    align: 'center',
    key: 'ds',
    dataIndex: 'ds',
    scopedSlots: { customRender: '锭数' },
  },
  {
    title: '定量',
    align: 'center',
    key: 'dl',
    dataIndex: 'dl',
    scopedSlots: { customRender: '定量' },
  },
  {
    title: '车速',
    align: 'center',
    key: 'cs',
    dataIndex: 'cs',
    scopedSlots: { customRender: '车速' },
  },
  {
    title: '效率',
    align: 'center',
    key: 'xiaolv',
    dataIndex: 'xiaolv',
    scopedSlots: { customRender: '效率' },
  },
  {
    title: '设定定额',
    align: 'center',
    key: 'weightSet',
    dataIndex: 'weightSet',
    scopedSlots: { customRender: '定额' },
  },
  {
    title: '细纱计划',
    width: 150,
    align: 'center',
    key: 'spunYarnOutput',
    dataIndex: 'spunYarnOutput',
  },
  // {
  //   title: '实开计划前(长度)8h',
  //   width: 200,
  //   align: 'center',
  //   key: 'output',
  //   dataIndex: 'output',
  // },
  {
    title: '临时计划(T)',
    width: 150,
    align: 'center',
    key: 'temOutput',
    dataIndex: 'temOutput',
  },
  {
    title: '计划产量前(T) 24h',
    width: 150,
    align: 'center',
    key: 'output',
    dataIndex: 'output',
  },
  {
    title: '甲A(T) 8h',
    align: 'center',
    key: 'aoutput',
    dataIndex: 'aoutput',
  },
  {
    title: '乙B(T) 8h',
    align: 'center',
    key: 'boutput',
    dataIndex: 'boutput',
  },
  {
    title: '丙C(T) 8h',
    align: 'center',
    key: 'coutput',
    dataIndex: 'coutput',
  },
  {
    title: '操作',
    align: 'center',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  mixins: [JeecgListMixin],
  components: { ShumianModal, ShuMianJiTaiModal },
  data() {
    return {
      currentMonth: moment(),
      title: '',
      queryParam: {
        planTime:moment().format('YYYY-MM-DD'),
        process: 2
      },
      columns,
      workHoursJa: 12,
      workHoursYb: 12,
      url: {
        list: path + '/list',
        delete: path + '/delete',
        deleteBatch: path + '/deleteBatch',
      }
    }
  },
  mounted() {

  },
  methods: {
    goPrev() {
      var newMonth = moment(this.currentMonth).subtract(1, 'day')
      this.currentMonth = newMonth
      this.queryParam.planTime = this.currentMonth.format('YYYY-MM-DD')
      this.searchQuery()
    },
    goNext() {
      var newMonth = moment(this.currentMonth).add(1, 'day')
      this.currentMonth = newMonth
      this.queryParam.planTime = this.currentMonth.format('YYYY-MM-DD')
      this.searchQuery()
    },
    onChangeDate(date, dateString) {
      this.queryParam.planTime = dateString
      this.searchQuery()
    },
    changeKt(e, type) {

    },
    showModal(records, param) {
      this.$refs.jitaiModal.show(records, param, false)
    },
    // 获取联系机台-粗纱
    getSeiresDevsnCs(arr) {
      if (arr) {
        const resultArray = this.processData(arr)
        let str = ''
        if (resultArray) {
          resultArray.map(item => {
            let itemStr = `${item.jc}：${this.getSeiresDevsn(item.devSnArea)}`
            // let itemStr = `一纺：${this.getSeiresDevsn(item.devSnArea)}`
            str += itemStr
          })
        }
        return str
      }
    },
    processData(array) {
      const groupedByWorkshop = array.reduce((acc, curr) => {
        // const workshop = curr.workshop
        const workshop = curr.workshopDictText
        const deviceNo = curr.deviceNo

        // 检查 acc 中是否已经存在 workshop 对应的项，如果不存在则创建一个新的项
        if (!acc[workshop]) {
          acc[workshop] = {
            jc: workshop, // 这里的 jc 是你想要的字段名，存放 workshop 的值
            devSnArea: [deviceNo] // 创建一个新的数组存放 deviceNo
          }
        } else {
          // 如果已经存在，则将当前 deviceNo 添加到对应的 devSnArea 中
          acc[workshop].devSnArea.push(deviceNo)
        }

        return acc
      }, {})

      // 对每个 devSnArea 数组按照 deviceNo 的大小排序
      for (let workshop in groupedByWorkshop) {
        groupedByWorkshop[workshop].devSnArea.sort((a, b) => parseInt(a) - parseInt(b))
      }
      // 将结果转换为数组形式
      const resultArray = Object.values(groupedByWorkshop)

      return resultArray
    },
    // 获取连续车台
    getSeiresDevsn(arr) {
      var result = [], i = 0, str = []
      if (arr) {
        result[i] = [arr[0]]
        arr.reduce(function (prev, cur) {
          parseInt(cur) - parseInt(prev) === 1
            ? result[i].push(cur)
            : (result[++i] = [cur])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str += `#${item[0]}~#${item[item.length - 1]}<br>`
          } else {
            str += `#${item[0]}<br>`
          }
        })
      } else {
        str = []
      }
      return str
    },
    selectChange(value, label, record) {
      console.log(value)
      console.log(label)
      let query = {
        id: record.id,
        workshop: label == 'workshop' ? value : record.workshop,
        floor: label == 'floor' ? value : record.floor,
        cproductType: label == 'cproductType' ? value : record.cproductType,
        // abProductType: label == 'abProductType' && value != '' ? value : null,
        // bbProductType: label == 'bbProductType' && value != '' ? value : null,
        "company": record.company,
        "adeviceIds": record.adeviceIds,
        "acProductType": record.acProductType,
        "bdeviceIds": record.bdeviceIds,
        "bcProductType": record.bcProductType,
        "cdeviceIds": record.cdeviceIds,
        "ccProductType": record.ccProductType,
        "unOpen": record.unOpen,
        "temOutput": record.temOutput,
        "speedSet": record.speedSet,
        "acStartTime": record.acStartTime,
        "acEndTime": record.acEndTime,
        "bcStartTime": record.bcStartTime,
        "bcEndTime": record.bcEndTime,
        "ccStartTime": record.ccStartTime,
        "ccEndTime": record.ccEndTime,
        "planTime": record.planTime,
        "process": record.process
      }
      editDailyPlanPreSpin(query).then((res) => {
        if (res.success) {
          this.$message.success('修改成功')
        }
        this.searchQuery()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.background {
  height: 100%;
  width: 100%;
  background-color: white;
  border-radius: 5px;
  box-shadow: 1px 4px 4px rgba(0, 0, 0, 0.05);
}

/* 去除Select组件的边框 */
/deep/ XiSha .ant-select-selection {
  display: block;
  box-sizing: border-box;
  background-color: #fafafa;
  border: 0;
  border-top-width: 1.02px;
  border-radius: 4px;
  outline: none;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/deep/ XiSha .ant-select-focused .ant-select-selection, .ant-select-selection:focus, .ant-select-selection:active {
  border-color: #fafafa;
  border-right-width: 1px !important;
  outline: 0;
  box-shadow: none;
}

.add-btn {
  width: 14px;
  height: 14px;
  padding: 0;
  text-align: center;
  line-height: 11px;
  border-radius: 2px;
  border: 1px solid #1790ff;
  color: #1790ff;
  font-size: 12px;
  cursor: pointer;
  margin-left: 4px;
}
</style>
